package com.dsp.services.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.core.cache.CacheInstance;
import com.core.util.DspUtil;
import com.core.util.GenericDAO;
import com.core.util.GenericServiceHibernate;
import com.dsp.bean.Company;
import com.dsp.bean.Employee;
import com.dsp.dao.CompanyDAO;
import com.dsp.services.CompanyService;
import com.dsp.services.EmployeeService;

@Service("companyService")
public class CompanyServiceImpl extends GenericServiceHibernate<Company, Long> implements CompanyService {

	Logger logger = Logger.getLogger(DspUtil.Log4J);

	private CompanyDAO companyDAO;

	@Resource(name = "companyDAO")
	public void setDao(GenericDAO<Company, Serializable> dao) {
		super.setDao(dao);
	}

	/**
	 * @return the companyDAO
	 */
	public CompanyDAO getCompanyDAO() {
		return companyDAO;
	}

	/**
	 * @param companyDAO
	 *            the companyDAO to set
	 */
	public void setCompanyDAO(CompanyDAO companyDAO) {
		this.companyDAO = companyDAO;
	}

	@Override
	public String save(Company entry) throws Exception {
		logger.debug("公司资料正在保存.......");
		DetachedCriteria dc = DetachedCriteria.forClass(Company.class);
		if (entry.getId() != null)
			dc.add(Restrictions.ne("id", entry.getId()));
		dc.add(Restrictions.eq("ccode", entry.getCcode()));
		List<Company> list = super.likeBy(dc);
		if (DspUtil.isEmptyList(list)) {
			super.save(entry);
			//刷新缓存
			CacheInstance.getInstance().refreshComapnyMap(entry.getId().toString(), entry);
			return null;
		}
		throw new RuntimeException("公司资料重复,请检查");
	}
	@Override
	public String delete(Company entry) {
		EmployeeService employee = (EmployeeService)DspUtil.getBean("employeeService");
		DetachedCriteria dc = DetachedCriteria.forClass(Employee.class);
		dc.add(Restrictions.eq("company", entry.getId()));
		List<Employee> hasEmployee = employee.likeBy(dc);
		if (DspUtil.isEmptyList(hasEmployee)) {
			super.delete(entry);
			CacheInstance.getInstance().removeCompanyMap(entry.getId().toString());
			return null;
		}
		return "该公司中已存在" + hasEmployee.size() +" 个员工,若要删除,请先删除员工数据!";
	}
}
